package com.andreas.controller;

import com.google.code.kaptcha.Producer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @Author andreaszhou
 * @ClassName KaptchaController
 * @Description TODO
 * @date 2021/1/21 9:31
 * @Version 1.0
 */
@Controller
public class KaptchaController {
    @Resource
    private Producer defaultKaptcha;
    @GetMapping("/verifyCode")
    public void createVerifyCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 不缓存任何图片数据
        response.setHeader("Cache-Control", "no-store,no-cache,must-revalidate");
        response.setHeader("Cache-Control", "post-check=0,pre-check=0");
        response.setHeader("Pragma", "no-cache");
        // 设置过期时间
        response.setDateHeader("Expires", 0);
        //设置返回的数据的类型
        response.setContentType("image/png");
        // 生成验证码的文本
        String text = defaultKaptcha.createText();
        // 将文本的验证码放入到session中
        request.getSession().setAttribute("kaptchaVerifyCode",text);
        System.out.println(request.getSession().getAttribute("kaptchaVerifyCode"));
        // 生成验证码的图片--创建验证码图片
        BufferedImage image = defaultKaptcha.createImage(text);
        // 通过输出流，将图片给相应出来
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image,"png",outputStream);
        outputStream.flush();
        outputStream.close();
    }
}
